/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.*;
import com.rzico.basics.model.CompanyEmployeeVo;
import com.rzico.basics.model.ProductUploadVo;
import com.rzico.basics.service.*;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.util.StringUtils;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.*;
import lombok.var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * 产品档案控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "产品档案接口")
@RestController
@RequestMapping("/admin/product")
public class ProductAdminController extends BaseController {

    @Autowired
    private ProductService productService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private BomService bomService;

    @Autowired
    private JdProductService jdProductService;

    /**
     * 分页查询产品档案
     *
     * @return
    */
    @ApiOperation("分页查询产品档案")
    @GetMapping("/list")
    @ApiImplicitParams(
    {
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "supplierId", value = "供应商Id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "productCategory", value = "分类 id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "商品类型 {0:实物,1:虚拟,2:赠品}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "subType", value = "类型 {0.产品,1:套餐,2:水票,3.压桶}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sn", value = "条码/货号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deleted", value = "删除标志", dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "isMarketable", value = "是否上架", dataType = "Boolean", paramType = "query"),
            @ApiImplicitParam(name = "tagIds", value = "标签", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isList", value = "是否显示多规格", dataType = "Boolean", paramType = "query"),
    })
    public CommResult<Product> list(String startDate, String endDate,String keyword, Long [] tagIds, Long productCategory, Integer type,
                                    Integer subType, Boolean deleted, String name, String sn, Boolean isMarketable,
                                    Boolean isList,Long supplierId, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(startDate)){
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)){
            params.put("endDate", endDate);
        }
        if (deleted==null) {
            deleted = false;
        }
        params.put("deleted",deleted);
        if (null != isList){
            params.put("isList",isList);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        if (productCategory!=null) {
            if (productCategory==0) {
                params.put("productCategoryId", productCategory);
            } else {
                params.put("treePath", String.valueOf(productCategory));
            }
        }

        if (subType!=null) {
            params.put("subType",subType);
        }

        if (supplierId!=null) {
            params.put("supplierId",supplierId);
        }


        if (StringUtils.isNotEmpty(keyword)) {
            params.put("keyword",keyword);
        }


        if (type!=null) {
            params.put("type",type);
        }


        if (name!=null) {
            params.put("name",name);
        }


        if (sn!=null) {
            params.put("sn",sn);
        }

        if (isMarketable!=null) {
            params.put("isMarketable",isMarketable);
        }

        if (tagIds!=null && tagIds.length>0) {
            params.put("tagIds",tagIds);
        }


        //检查是否供应商账号
        SysUser sysUser = sysUserService.getCurrent();
        Supplier supplier = supplierService.findByUserId(sysUser.getId());
        if (supplier!=null) {
            params.put("supplierId",supplier.getId());
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Product> list = productService.selectList(params);
        PageResult<Product> pageResult = new PageResult<Product>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条产品档案
     *
     * @return
    */
    @ApiOperation("查询单条产品档案")
    @GetMapping("/find/{id}")
    public CommResult<Product> find(@PathVariable String id) {
        Product result = productService.findById(id);
        Map<String,Object> params = new HashMap<>();
        params.put("goodsId",result.getGoodsId());
        params.put("deleted",false);

        params.put("sortField", "is_list");
        params.put("sortType", "desc");

        List<Product> products = productService.selectList(params);

        Map<String,Object> articleParams = new HashMap<>();
        articleParams.put("goods",result.getGoodsId());

        Map<String,Object> data = new HashMap<>();
        data.put("products",products);
        data.put("article", result.getMetaAndContent());

        Product product = products.get(0);
        if (product.getBrandId()!=null) {
            Brand brand = brandService.findById(product.getBrandId());
            if (brand!=null) {
                data.put("brandName", brand.getName());
            }
        }

        if (product.getSupplierId()!=null) {
            Supplier supplier = supplierService.findById(product.getSupplierId());
            if (supplier!=null) {
                data.put("supplierName", supplier.getName());
            }
        }

        return CommResult.success(data);

    }

    /**
     * 按条码/货号查询单条产品档案
     *
     * @return
     */
    @ApiOperation("按条码/货号查询单条产品档案")
    @GetMapping("/findBySn")
    public CommResult<Product> findBySn(String sn) {
        Map<String,Object> params = new HashMap<>();
        params.put("sn",sn);
        List<Product> products = productService.selectList(params);
        if (products.size()>0) {
            Map<String,Object> data = new HashMap<>();
            data.put("products",products);
            return CommResult.success(data);
        } else {
            return CommResult.error("无效条码");
        }

    }

    /**
     * 保存产品档案
     *
     * @param list
     * @return
     */
    @ApiOperation("保存产品档案")
    @PostMapping("/save")
    public CommResult<Product> save(@RequestBody List<Product> list,Long[] tagIds) {
        Assert.notNull(list, "商品信息为空");
        Enterprise enterprise = enterpriseService.getCurrent();
        for (Product product:list) {
            product.setIsMarketable(false);
            if (product.getSn()==null) {
                return CommResult.error("货号不能为空");
            }
            if (product.getUnit()==null) {
               return CommResult.error("单位不能为空");
            }
            product.setPublishType(0);
            if (product.getOrders()==null) {
                product.setOrders(99);
            }
            product.setEnterpriseId(enterprise.getId());
        }
        List<Product> productList = productService.insertProduct(list,tagIds);

        Map<String,Object> params = new HashMap<>();
        params.put("goodsId",productList.get(0).getGoodsId());
        params.put("deleted",false);
        params.put("sortField","is_list");
        params.put("sortType","desc");
        productList = productService.selectList(params);

        return CommResult.success(productList);

    }



    /**
     * 复制商品
     *
     * @param productId
     * @return
     */
    @Log(desc = "复制商品", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("复制商品")
    @PostMapping("/copyProduct")
    public CommResult<Bom> copyProduct(Long productId) {

        Enterprise enterprise = enterpriseService.getCurrent();

        Product product = productService.selectByPrimaryKey(productId);
        if (product==null) {
            return CommResult.error("无效商品");
        }

        List<Product> productList = productService.findBySn(enterprise,product.getSn());
        if (productList.size()>0) {
            return CommResult.error("货号已经存在");
        }

        List<Product> result = productService.copyProduct(enterprise,product);

        return CommResult.success(result);

    }

    /**
     * 批量删除产品档案
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除产品档案", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除产品档案,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Product> del(@PathVariable String ids) {

        productService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新产品档案
     *
     * @param product
     * @return
     */
    @Log(desc = "更新产品档案", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新产品档案")
    @PostMapping("/updateProduct")
    public CommResult<Product> updateProduct(@RequestBody Product product) {

        Assert.notNull(product.getId(), "商品唯一编码为空");
        Assert.notNull(product.getIsMarketable(), "是否上架参数为空");

        int affectCount = productService.updateByPrimaryKeySelective(product);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Product prod = productService.selectByPrimaryKey(product.getId());
        if (!prod.getPublishType().equals(0)) {
            product.setSn(null);
        }
        if (product.getIsMarketable()) {

           if (prod.getType().equals(2)) {
               if (prod.getPoint() == 0) {
                   return CommResult.error("积分审核后才能上架");
               }
           } else {
               if (prod.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                   return CommResult.error("价格审核后才能上架");
               }
           }

           if (prod.getSubType().equals(1)) {

                        //套餐时，生成配送计划
                        Bom bom = null;
                        Map<String, Object> params = new HashMap<>();
                        params.put("enterpriseId", prod.getEnterpriseId());
                        params.put("productId", prod.getId());
                        List<Bom> bomList = bomService.selectList(params);
                        if (bomList.size() > 0) {
                            bom = bomList.get(0);
                        }

                        if (bom == null) {
                            return CommResult.error("请设置套餐");
                        }

            }

        }
        /**
         * 京东商品上架时，判断该商品下所有sku的可售性，上下架状态及库存数量，若未上架、不可售或库存不足，系统中商品库存数量直接设为0
         */
        if (prod.getSn().contains("jd") && product.getIsMarketable()) {
            Enterprise enterprise = enterpriseService.getCurrent();
            jdProductService.checkJdProduct(prod.getGoodsId(), enterprise.getMchId());
        }

        productService.updateMarketable(prod.getGoodsId(),product.getIsMarketable());
        Product pdt = productService.findById(product.getId());
        return CommResult.success(pdt);
    }

    /**
     * 批量更新商品档案/分类，上下架
     *
     * @param products
     * @return
     */
    @Log(desc = "批量更新商品档案/分类，上下架", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("批量更新商品档案/分类，上下架")
    @PostMapping("/BatchUpdate")
    public CommResult<Product> BatchUpdate(@RequestBody List<Product> products) {
        List<Product> productList = new ArrayList<>();
        for (Product product:products) {
            Product prod = productService.selectByPrimaryKey(product.getId());
            if (product.getIsMarketable()!=null) {
                prod.setIsMarketable(product.getIsMarketable());
            }
            if (product.getProductCategoryId()!=null) {
                prod.setProductCategoryId(product.getProductCategoryId());
            }
            if (prod.getIsMarketable()) {

                if (prod.getType().equals(2)) {
                    if (prod.getPoint() == 0) {
                        return CommResult.error("积分审核后才能上架");
                    }
                } else {
                    if (prod.getPrice().compareTo(BigDecimal.ZERO) == 0) {
                        return CommResult.error("价格审核后才能上架");
                    }
                }

                if (prod.getSubType().equals(1)) {

                    //套餐时，生成配送计划
                    Bom bom = null;
                    Map<String, Object> params = new HashMap<>();
                    params.put("enterpriseId", prod.getEnterpriseId());
                    params.put("productId", prod.getId());
                    List<Bom> bomList = bomService.selectList(params);
                    if (bomList.size() > 0) {
                        bom = bomList.get(0);
                    }

                    if (bom == null) {
                        return CommResult.error("请设置套餐");
                    }

                }

            }
            /**
             * 京东商品上架时，判断该商品下所有sku的可售性，上下架状态及库存数量，若未上架、不可售或库存不足，系统中商品库存数量直接设为0
             */
            if (prod.getSn().contains("jd") && product.getIsMarketable()) {
                Enterprise enterprise = enterpriseService.getCurrent();
                jdProductService.checkJdProduct(prod.getGoodsId(), enterprise.getMchId());
            }

            productList.add(prod);

        }

        productService.batchUpdate(productList);

        return CommResult.success("操作成功");
    }

    /**
     * 批量添加/删除标签
     *
     * @param products
     * @return
     */
    @Log(desc = "批量上下架产品，1.添加；0.删除", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("批量上下架产品，1.添加；0.删除")
    @PostMapping("/batchUpdateProducts")
    public CommResult<Product> batchUpdateProductsTag(@RequestBody List<Product> products,Long[] tagIds, String type) {
        Assert.notNull(products, "商品信息为空");
        productService.batchUpdateProductsTag(products, tagIds, type);
        return CommResult.success(products);
    }

    /**
     * 批量更新产品档案
     *
     * @param products
     * @return
     */
    @Log(desc = "批量更新产品档案", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("批量更新产品档案")
    @PostMapping("/update")
    public CommResult<Product> update(@RequestBody List<Product> products,Long[] tagIds) {

        Assert.notNull(products, "商品信息为空");

        Enterprise enterprise = enterpriseService.getCurrent();

        Long mainProductId = null;

        for (Product product : products){
            if (product.getIsList()){
                mainProductId = product.getId();
                break;
            }
        }

        for (Product product:products) {
            product.setIsMarketable(false);
            if (product.getSn()==null) {
                return CommResult.error("货号不能为空");
            }
            if (product.getUnit()==null) {
                return CommResult.error("单位不能为空");
            }
            if (product.getGoodsId()==null) {
                return CommResult.error("goodsId不能为空");
            }
            product.setPublishType(products.get(0).getPublishType());
            if (product.getPublishType()==null) {
                product.setPublishType(0);
            }
            if (product.getOrders()==null) {
                product.setOrders(99);
            }
        }

        int affectCount = productService.updateProduct(products,tagIds);
        if (affectCount <= 0){
            return CommResult.error();
        }

        Map<String,Object> params = new HashMap<>();
        params.put("goodsId",products.get(0).getGoodsId());
        params.put("deleted",false);
        params.put("sortField","is_list");
        params.put("sortType","desc");
        List<Product> productList = productService.selectList(params);
        return CommResult.success(productList);

    }

    /**
     * 导入产品档案
     *
     * @param list
     * @return
     */
    @Log(desc = "导入产品档案", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("导入产品档案")
    @PostMapping("/upload")
    public CommResult<ProductUploadVo> upload(@RequestBody List<ProductUploadVo> list, String ModifyBy,Long enterpriseId){
        Enterprise enterprise = enterpriseService.getCurrent();
        if (null == enterprise) {
            return CommResult.error("没有开通企业");
        }

        var uploadList=productService.upload(list,ModifyBy,enterpriseId);
        return CommResult.success(uploadList);
    }

    public static void main(String[] args) {
        try {
            System.out.println(URLDecoder.decode(URLDecoder.decode("%25E5%25B9%25B2", "utf-8"),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


}
